<template>
  <div>
    <el-input
      ref="content"
      type="textarea"
      :rows="3.5"
      v-model="content"
      class="no-resize m-r-10 bilibili"
      :id="id"
    />
    <div class="flex content-space-between m-t-10 m-b-5">
      <div>
        <el-popover placement="bottom" width="400" trigger="click">
          <emoji @emoji="handleEmoji" />
          <el-button slot="reference" size="mini" round>
            <svg-icon icon-name="emoji"/>&nbsp;表情
          </el-button>
        </el-popover>
      </div>
      <el-button-group>
        <el-button
          size="small"
          type="primary"
          @click="onSubmit"
          :loading="loading"
          :disabled="empty"
          round
        >确定</el-button>
        <el-button size="small" @click="cancelEdit" round>取消</el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script>
import { formatComment } from './format';

export default {
  name: 'comment-edit', // 编辑回复
  props: ['edit', 'floor'],
  data() {
    return {
      content: this.floor.content.replace(/<\/?.+?\/?>/g, ''),
      loading: false,
      id: new Date().getTime(),
    };
  },
  computed: {
    empty() { return !this.content.trim(); },
  },
  methods: {
    onSubmit() {
      this.loading = true;
      this.$api.comments.update({
        commentId: this.floor.id,
        content: this.content.trim(),
      }).then((res) => {
        this.$message.success('修改成功');
        this.$emit('updatedComment', formatComment(res.data));
        this.cancelEdit();
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    cancelEdit() { this.$emit('update:edit', false); },
    onFocus() { this.$refs.content.focus(); },
    handleEmoji(item) {
      const inputArea = document.getElementById(this.id);
      function changeSelectedText(obj, str) {
        if (window.getSelection) {
          inputArea.setRangeText(str);
          inputArea.selectionStart += str.length;
          inputArea.focus();
        } else if (document.selection) {
          obj.focus();
          const sel = document.selection.createRange();
          sel.text = str;
        }
      }
      changeSelectedText(inputArea, item);
      this.content = inputArea.value;
    },
  },
};
</script>

<style></style>
